/*
 * main.cpp
 *
 *  Created on: May 8, 2013
 *      Author: r.leonov
 */


#include "kl_lib_l15x.h"
#include "led_indicate.h"
#include "main.h"
#include "usb.h"
#include "device.h"
#include "adc.h"
#include "cstdlib"

void GeneralInit(void);


int main(void){
    // Init
	GeneralInit();
	PinSetupIn(GPIOA, 0, pudNone);

	uint32_t Tmr, value;



	while(1){
	    // App
	    Tree.Task();
	    TreeLed.Task();
	    if(Delay.Elapsed(&Tmr, 999)){

	        value = rand()%100;
	        Uart.Printf("%u\r", value);
	    }
	    // Service
	    Uart.Task();
	    Adc.Task();
    }
}

void GeneralInit(void){
	SystemCoreClockUpdate();
	// Init Delay
	Delay.Init();
//    Delay.ms(125);
//    Adc.Init();
    // Init First branch of LED
    TreeLed.Init(1000);
	// Uart Init
	Uart.Init(500000);
	// Init Tree at all
    Tree.Init();
    // How need to start
	if(!(PWR->CSR & PWR_CSR_SBF)) {    // Wake up from StndBy mode
	    Uart.Printf("\rIlumelasse v.%u\r", CURRENT_FW_VER);
	} else PWR->CR |= PWR_CR_CSBF;     // Clear Wakeup SBF flag
    Tree.State = tsWakeup;
    Uart.Printf("tsWakeup\r");

	//	Usb.Init();
//	Usb.IConnect();
}


void StandBy(void){
    PWR->CR = 0;
    PWR->CR |= PWR_CR_CWUF;         // Clear Wakeup flag
    PWR->CR |= PWR_CR_PDDS;         // Select STANDBY mode
    PWR->CSR |= PWR_CSR_EWUP1;      // Enable WUP1 Pin for WakeUp
    SCB->SCR |= SCB_SCR_SLEEPDEEP;  // Set SLEEPDEEP bit of Cortex System Control Register
    __WFI();
}
